// 意见反馈管理
import React, { Fragment, useState, useEffect } from 'react';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import PropTypes from 'prop-types';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import { withStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableFooter from '@material-ui/core/TableFooter';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import MenuItem from '@material-ui/core/MenuItem';
import TablePagination from '@material-ui/core/TablePagination';
import IconButton from '@material-ui/core/IconButton';
import FirstPageIcon from '@material-ui/icons/FirstPage';
import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft';
import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight';
import LastPageIcon from '@material-ui/icons/LastPage';
import DateFnsUtils from '@date-io/date-fns';
import {
    MuiPickersUtilsProvider,
    DatePicker
} from '@material-ui/pickers';
import 'date-fns';
import zhCNLocale from "date-fns/locale/zh-CN";


import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import Avatar from '@material-ui/core/Avatar';
import GridList from '@material-ui/core/GridList';
import GridListTile from '@material-ui/core/GridListTile';

import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';

import logo from '../../../logo.svg';
// 缩略图
import thumbnail from '../../../assets/images/timg (1).jpg';
// 表格标题样式
import fetch from '../../../assets/utils/fetch'

const StyledTableCell = withStyles(theme => ({
    head: {
        // backgroundColor: '#47484c',
        color: '#333',
        fontWeight: 'bold'
    }
}))(TableCell);

const useStyles = makeStyles(theme => ({
    container: {
        display: 'flex',
        flexWrap: 'wrap',
    },
    button: {
        margin: theme.spacing(1),
    },
    textField: {
        marginLeft: theme.spacing(1),
        marginRight: theme.spacing(1),
        width: 200,
    },
    dense: {
        marginTop: 19,
    },
    menu: {
        width: 200,
    },
}));

const useStyles1 = makeStyles(theme => ({
    root: {
        flexShrink: 0,
        color: theme.palette.text.secondary,
        marginLeft: theme.spacing(2.5),
    },
}));

// 分页控制器
function TablePaginationActions(props) {
    const classes = useStyles1();
    const theme = useTheme();
    const { count, page, rowsPerPage, onChangePage } = props;

    function handleFirstPageButtonClick(event) {
        onChangePage(event, 0);
    }

    function handleBackButtonClick(event) {
        onChangePage(event, page - 1);
    }

    function handleNextButtonClick(event) {
        onChangePage(event, page + 1);
    }

    function handleLastPageButtonClick(event) {
        onChangePage(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
    }

    return (
        <div className={classes.root}>
            <IconButton
                onClick={handleFirstPageButtonClick}
                disabled={page === 0}
                aria-label="first page"
            >
                {theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />}
            </IconButton>
            <IconButton onClick={handleBackButtonClick} disabled={page === 0} aria-label="previous page">
                {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />}
            </IconButton>
            <IconButton
                onClick={handleNextButtonClick}
                disabled={page >= Math.ceil(count / rowsPerPage) - 1}
                aria-label="next page"
            >
                {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />}
            </IconButton>
            <IconButton
                onClick={handleLastPageButtonClick}
                disabled={page >= Math.ceil(count / rowsPerPage) - 1}
                aria-label="last page"
            >
                {theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />}
            </IconButton>
        </div>
    );
}

TablePaginationActions.propTypes = {
    count: PropTypes.number.isRequired,
    onChangePage: PropTypes.func.isRequired,
    page: PropTypes.number.isRequired,
    rowsPerPage: PropTypes.number.isRequired,
};

function FormDialog(props) {
    function hide(){
        if(props.hideFormDialog) props.hideFormDialog();
    }

    function ok(){
        setTimeout(() =>{
            hide();
        },300);
    }
    function no(){
        hide();
    }

    return (
        <div>
            <Dialog open={props.show} onClose={hide} aria-labelledby="form-dialog-title">
                <DialogTitle id="form-dialog-title">意见处理</DialogTitle>
                <DialogContent style={{width:'400px'}}>
                    <TextField
                        autoFocus
                        margin="dense"
                        id="name"
                        label="处理方式"
                        type="text"
                        fullWidth
                    />
                </DialogContent>
                <DialogActions>
                    <Button onClick={no} color="primary">
                        取消
                    </Button>
                    <Button onClick={ok} color="primary">
                        确定
                    </Button>
                </DialogActions>
            </Dialog>
        </div>
    );
}
// 处理反馈
function DoWork(props) {
    function doWork() {
        if(props.showFormDialog) props.showFormDialog();
    }
    return (
        <span onClick={doWork} style={{ color: 'rgb(60, 154, 255)', cursor: 'pointer' }}>处理</span>
    )
}

/**
 * 创建一行数据
 * @param {object} feedBack 意见反馈
 * @param {number} type 类型 
 * @param {React.Component} doSomething 组件（操作） 
 */
function createData(feedBack, type, doSomething) {
    return {
        feedBack,
        type: '小区物业',//TODO:这先写死
    };
}

let feedBack = {
    headimg: logo,//头像
    name: '李光光', //标题
    title: '我家水龙头坏了，来帮我修修呗',
    thumbnails: [thumbnail, thumbnail], //缩略图
    date_time: '',   //日期
    phoneNumber: '', //手机号
    type: 1,         //类型
}

// table数据
const rows = [
    createData(feedBack, 1),
    createData(feedBack, 1),
    createData(feedBack, 1),
    createData(feedBack, 1),
    createData(feedBack, 1),
    createData(feedBack, 1),
];

const useStyles2 = makeStyles(theme => ({
    root: {
        width: '100%',
        marginTop: theme.spacing(4),
    },
    table: {
        minWidth: 500,
        height: 500,
    },
    tableWrapper: {
        overflowX: 'auto',
    },
}));
const ListStyle = makeStyles(theme => ({
    root: {
        width: '100%',
        backgroundColor: theme.palette.background.paper,
    },
    inline: {
        display: 'inline',
    },
}));

const GridListStyle = makeStyles(theme => ({
    root: {
        display: 'flex',
        flexWrap: 'wrap',
        justifyContent: 'space-around',
        overflow: 'hidden',
        backgroundColor: theme.palette.background.paper,
        marginTop: theme.spacing(1)
    },
    gridList: {
        //   width: 500,
        //   height: 450,
        //   maxWidth:300,
    },
}));

// 自定义分页表格
function CustomPaginationActionsTable(props) {
    const classes = useStyles2();
    const listStyle = ListStyle();
    const gridListStyle = GridListStyle();

    const [page, setPage] = React.useState(0);
    const [rowsPerPage, setRowsPerPage] = React.useState(5);

    const emptyRows = rowsPerPage - Math.min(rowsPerPage, rows.length - page * rowsPerPage);

    function handleChangePage(event, newPage) {
        setPage(newPage);
    }

    function handleChangeRowsPerPage(event) {
        setRowsPerPage(parseInt(event.target.value, 10));
        setPage(0);
    }

    return (
        <Paper className={classes.root}>
            <div className={classes.tableWrapper}>
                <Table className={classes.table}>
                    <TableHead>
                        <TableRow>
                            <StyledTableCell>意见反馈</StyledTableCell>
                            <StyledTableCell>类型</StyledTableCell>
                            <StyledTableCell>操作</StyledTableCell>
                        </TableRow>
                    </TableHead>
                    <TableBody>
                        {props.dataList.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row, index) => (
                            <TableRow key={index}>
                                <TableCell component="th" scope="row">
                                    <List className={listStyle.root}>
                                        <ListItem alignItems="flex-start">
                                            <ListItemAvatar>
                                                <Avatar alt="Remy Sharp" src={row.logo} />
                                            </ListItemAvatar>
                                            <div className="________" style={{WebkitFlex:'1',flex:'1'}}>
                                                <ListItemText
                                                    primary={row.user_name}
                                                    secondary={row.content}
                                                />
                                                <ListItemText>
                                                    <GridList cellHeight={100} className={gridListStyle.gridList} cols={6}>
                                                        {row.pic.map((thumbnail, index) => (
                                                            <GridListTile key={index} cols={1}>
                                                                <img src={thumbnail} />
                                                            </GridListTile>
                                                        ))}
                                                    </GridList>
                                                </ListItemText>
                                                <ListItemText
                                                    secondary={
                                                        <React.Fragment>
                                                            <span>{row.created}</span>
                                                            <span style={{marginLeft:'20px'}}>{row.phone || ''}</span>
                                                        </React.Fragment>
                                                    }
                                                />
                                            </div>
                                        </ListItem>
                                    </List>
                                </TableCell>
                                <TableCell style={{ width: '180px' }}>小区物业</TableCell>
                                <TableCell style={{ width: '180px' }}>
                                    <DoWork
                                        showFormDialog={props.showFormDialog}
                                        hideFormDialog={props.hideFormDialog}
                                    />
                                </TableCell>
                            </TableRow>
                        ))}

                        {emptyRows > 0 && (
                            <TableRow style={{ height: 48 * emptyRows }}>
                                <TableCell />
                            </TableRow>
                        )}
                    </TableBody>
                    <TableFooter>
                        <TableRow>
                            <TablePagination
                                rowsPerPageOptions={[5, 10]}
                                colSpan={12}
                                count={rows.length}
                                rowsPerPage={rowsPerPage}
                                page={page}
                                SelectProps={{
                                    inputProps: { 'aria-label': 'rows per page' },
                                    native: true,
                                }}
                                onChangePage={handleChangePage}
                                onChangeRowsPerPage={handleChangeRowsPerPage}
                                ActionsComponent={TablePaginationActions}
                            />
                        </TableRow>
                    </TableFooter>
                </Table>
            </div>
        </Paper>
    );
}
// 日期选择器样式
const dateStyle = makeStyles(theme => ({
    root: {
        marginTop: theme.spacing(2),
        marginLeft: theme.spacing(1),
        marginRight: theme.spacing(1),
    },
}));
// 日期选择器
function InlineDatePickerDemo(props) {
    const classes = dateStyle();
    const [selectedDate, handleDateChange] = useState(new Date());
    return (
        <Fragment>
            <MuiPickersUtilsProvider utils={DateFnsUtils} locale={zhCNLocale}>
                <DatePicker
                    className={classes.root}
                    variant="inline"
                    label="开始日期"
                    value={selectedDate}
                    onChange={handleDateChange}
                    format="yyyy/MM/dd/"
                />
                <DatePicker
                    className={classes.root}
                    variant="inline"
                    label="结束日期"
                    value={selectedDate}
                    onChange={handleDateChange}
                    format="yyyy/MM/dd/"
                />
            </MuiPickersUtilsProvider>
        </Fragment>
    );
}


export default function App(props) {
    const classes = useStyles();
    // 搜索对象
    const [searchs, setSearchs] = React.useState({
        startDate: '',
        endDate: '',
        status: '0',
    })
    const [feedBack, setFeedBack] = useState([]);
    // formDialog显示与否
    const [formDialog,setFormDialog] = React.useState(false);
    // 搜索中状态的几种
    const statuss = [
        {
            value: '0',
            label: '全部'
        },
        {
            value: '1',
            label: '未处理'
        },
        {
            value: '2',
            label: '已处理'
        },
    ]
    

    
    function showFormDialog(){
        setFormDialog(true);
    }
    function hideFormDialog(){
        setFormDialog(false);
    }

    // 输入框变化 更新搜索对象
    const handleChange = name => event => {
        console.log(event.target)
        var _searchs = searchs;
        _searchs[name] = event.target.value;
        setSearchs({ ..._searchs })
    };
    // 提交搜索
    function handleSearch() {
        console.log(searchs);
    }

    function getFeedBack(){
        fetch.getJson('/self/server/feed_back/getFeedBack?agent_id=1',(err,res) =>{
            if(err){
                console.error(err);
            }
            else{
                if(res.code == 1){
                    if(res.data.feed_back instanceof Array){
                        // 缩略图是多张图片地址拼成的字符串，为了页面中循环渲染，将它成切成数组
                        setFeedBack(res.data.feed_back.map((item) =>{
                            if(item.pic){
                                item.pic = item.pic.split(',');
                            }
                            else{
                                item.pic = [];
                            }
                            return item;
                        }));
                    }
                }
            }
        })
    }
    useEffect(() => {
        getFeedBack();
    },[]);


    return (
        <div className="main-page-content">
            {/* 搜索模块 */}
            <div className={classes.container} noValidate autoComplete="off" style={{ textAlign: 'right' }}>
                {/* 日期选择器 */}
                <InlineDatePickerDemo />
                <TextField
                    id="standard-select-currency"
                    select
                    label="状态"
                    className={classes.textField}
                    value={searchs.status}
                    onChange={handleChange('status')}
                    margin="normal"
                >
                    {statuss.map(option => (
                        <MenuItem key={option.label} value={option.value} style={{ background: '#fff' }}>
                            {option.label}
                        </MenuItem>
                    ))}
                </TextField>
                <Button onClick={handleSearch} variant="contained" color="primary" className={classes.button} style={{ WebkitAlignSelf: 'flex-end', alignSelf: 'flex-end', height: '40px' }}>
                    搜索
                </Button>
            </div>
            {/* 自定义带分页表格 */}
            <CustomPaginationActionsTable
                showFormDialog={showFormDialog}
                hideFormDialog={hideFormDialog}
                dataList={feedBack}
            />
            {/* 意见处理对话框 */}
            <FormDialog 
                show={formDialog}
                showFormDialog={showFormDialog}
                hideFormDialog={hideFormDialog}
            />
        </div>
    )
}